package com.kun.service.service;

import cn.hutool.extra.spring.SpringUtil;
import com.kun.auth.LoginUser;
import com.kun.domain.SysUser;
import com.kun.enums.UserStatus;
import com.kun.utils.SecurityUtils;
import com.kun.utils.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

import java.util.Set;

@Slf4j
@Service
public class LoginService implements UserDetailsService {

    private final TokenService tokenService;
    private final ISysUserService userService;
    private final SysPasswordService sysPasswordService;
    private final SysPermissionService permissionService;

    public LoginService(TokenService tokenService, ISysUserService userService, SysPasswordService sysPasswordService,
                        SysPermissionService permissionService) {
        this.tokenService = tokenService;
        this.userService = userService;
        this.sysPasswordService = sysPasswordService;
        this.permissionService = permissionService;
    }

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        SysUser user = userService.selectUserByUserName(username);
        Assert.isTrue(StringUtils.isNotNull(user), "登录用户：" + username + " 不存在");
        Assert.isTrue(!UserStatus.DELETED.getCode().equals(user.getDelFlag()), "登录用户：" + username + " 已被删除");
        Assert.isTrue(!UserStatus.DISABLE.getCode().equals(user.getStatus()), "登录用户：" + username + " 已被停用");
        sysPasswordService.validate(user);
        return createLoginUser(user);
    }

    /**
     * 登录
     */
    public String login(SysUser user) {
        UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(user.getName(), user.getPassword());
        SecurityContextHolder.getContext().setAuthentication(authenticationToken);
        AuthenticationManager authenticationManager = SpringUtil.getBean(AuthenticationManager.class);
        Authentication authenticate = authenticationManager.authenticate(authenticationToken);
        LoginUser loginUser = (LoginUser) authenticate.getPrincipal();

        // 更新权限
        UsernamePasswordAuthenticationToken newAuthenticationToken =
                new UsernamePasswordAuthenticationToken(authenticate.getPrincipal(), authenticate.getCredentials(),
                        loginUser.getAuthorities());
        SecurityContextHolder.getContext().setAuthentication(newAuthenticationToken);
        // 生成token
        return tokenService.createToken(loginUser);
    }

    public UserDetails createLoginUser(SysUser user) {
        Set<String> menuPermission = permissionService.getMenuPermission(user);
        // 获取角色权限
        menuPermission.add("ROLE_" + "ACTIVITI_USER");
        return new LoginUser(user.getUserId(), user.getDeptId(), user, menuPermission);
    }

}
